from flask import Flask, render_template
from config import Config
from extensions import db, login_manager
from models.user import User
from routes.auth import auth_bp
from routes.user import user_bp
from routes.order import order_bp
from routes.storage import storage_bp
from routes.service import service_bp
from routes.quality import quality_bp
from routes.finance import finance_bp
from routes.safety import safety_bp

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(user_bp)
    app.register_blueprint(order_bp)
    app.register_blueprint(storage_bp)
    app.register_blueprint(service_bp, url_prefix='/service')
    app.register_blueprint(quality_bp, url_prefix='/quality')
    app.register_blueprint(finance_bp, url_prefix='/finance')
    app.register_blueprint(safety_bp, url_prefix='/safety')

    @app.route('/')
    def index():
        user_count = User.query.count()
        return render_template('index.html', user_count=user_count)

    return app

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        db.create_all()
    app.run(debug=True, host='0.0.0.0', port=5000) 